#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
贝壳OC智能应用中心 - Python后端代理服务
解决前端跨域问题，提供API代理和图片代理功能
"""

from flask import Flask, request, jsonify, Response
from flask_cors import CORS
import requests
import os
import logging
from urllib.parse import unquote

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)

# 配置CORS
if os.getenv('FLASK_ENV') == 'production':
    # 生产环境：严格的CORS策略
    CORS(app, origins=[
        'https://aioc.ke.com',
        'https://www.aioc.ke.com'
    ], supports_credentials=True)
else:
    # 开发环境：宽松的CORS策略
    CORS(app, origins='*', supports_credentials=True)

# 扣子API配置
COZE_API_TOKEN = 'pat_9Ydl8c51bougw6nBTxUhXbDweMnYKdbkzTSfY9TkMYNbe5ZZ9hNLnzmbHyw3r9zW'
COZE_API_URL = 'https://api.coze.cn/open_api/v2/chat'

@app.route('/api/coze-proxy', methods=['POST', 'OPTIONS'])
def coze_proxy():
    """扣子API代理端点"""
    if request.method == 'OPTIONS':
        # 处理预检请求
        return '', 200
    
    try:
        # 获取请求数据
        request_data = request.get_json()
        
        if not request_data:
            return jsonify({'error': '请求数据为空'}), 400
        
        logger.info(f"代理扣子API请求: {request_data}")
        
        # 发送请求到扣子API
        headers = {
            'Authorization': f'Bearer {COZE_API_TOKEN}',
            'Content-Type': 'application/json'
        }
        
        response = requests.post(
            COZE_API_URL,
            json=request_data,
            headers=headers,
            timeout=30
        )
        
        # 返回响应
        if response.status_code == 200:
            return jsonify(response.json())
        else:
            logger.error(f"扣子API错误: {response.status_code} - {response.text}")
            return jsonify({
                'error': f'API调用失败: {response.status_code}',
                'message': response.text
            }), response.status_code
            
    except requests.exceptions.Timeout:
        logger.error("扣子API请求超时")
        return jsonify({'error': 'API请求超时'}), 504
    except requests.exceptions.RequestException as e:
        logger.error(f"扣子API请求异常: {str(e)}")
        return jsonify({'error': f'网络请求失败: {str(e)}'}), 500
    except Exception as e:
        logger.error(f"代理服务异常: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@app.route('/api/image-proxy', methods=['GET', 'OPTIONS'])
def image_proxy():
    """图片代理端点"""
    if request.method == 'OPTIONS':
        return '', 200
    
    try:
        # 获取图片URL参数
        image_url = request.args.get('url')
        
        if not image_url:
            return jsonify({'error': '缺少url参数'}), 400
        
        # URL解码
        image_url = unquote(image_url)
        logger.info(f"代理图片请求: {image_url}")
        
        # 请求图片
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        response = requests.get(
            image_url,
            headers=headers,
            timeout=30,
            stream=True
        )
        
        if response.status_code == 200:
            # 获取内容类型
            content_type = response.headers.get('content-type', 'image/jpeg')
            
            # 创建响应
            def generate():
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        yield chunk
            
            return Response(
                generate(),
                content_type=content_type,
                headers={
                    'Cache-Control': 'public, max-age=86400',
                    'Access-Control-Allow-Origin': '*'
                }
            )
        else:
            logger.error(f"图片请求失败: {response.status_code}")
            return jsonify({'error': f'图片加载失败: {response.status_code}'}), response.status_code
            
    except requests.exceptions.Timeout:
        logger.error("图片请求超时")
        return jsonify({'error': '图片请求超时'}), 504
    except requests.exceptions.RequestException as e:
        logger.error(f"图片请求异常: {str(e)}")
        return jsonify({'error': f'图片加载失败: {str(e)}'}), 500
    except Exception as e:
        logger.error(f"图片代理异常: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({
        'status': 'healthy',
        'service': '贝壳OC智能应用中心代理服务',
        'version': '1.0.0',
        'environment': os.getenv('FLASK_ENV', 'development')
    })

@app.route('/', methods=['GET'])
def index():
    """根路径"""
    return jsonify({
        'message': '贝壳OC智能应用中心代理服务',
        'endpoints': {
            'coze_proxy': '/api/coze-proxy',
            'image_proxy': '/api/image-proxy',
            'health': '/health'
        }
    })

if __name__ == '__main__':
    # 获取环境变量
    port = int(os.getenv('PORT', 3000))
    debug = os.getenv('FLASK_ENV') != 'production'
    
    logger.info(f"启动代理服务器，端口: {port}")
    logger.info(f"环境: {'生产' if not debug else '开发'}")
    
    # 生产环境建议使用gunicorn等WSGI服务器
    if debug:
        app.run(host='0.0.0.0', port=port, debug=debug)
    else:
        # 生产环境配置
        app.run(host='0.0.0.0', port=port, debug=False, threaded=True)